package top.xizai.wrr.wrr.impl;

import top.xizai.wrr.Element;
import top.xizai.wrr.wrr.IWrr;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @NAME: WSC
 * @DATE: 2021/12/27
 * @DESCRIBE:
 **/
public class WrrIncrement implements IWrr {
    private final Element[] elements;
    private final int total;
    private AtomicInteger count;

    public WrrIncrement(Element[] elements) {
        this.elements = elements;

        this.total = Arrays.stream(elements)
                        .mapToInt(Element::getWeight)
                        .sum();

        count = new AtomicInteger();
    }

    @Override
    public String next() {
        int len = elements.length;
        int index = len - 1;
        int hit = count.getAndIncrement() % total;

        for (int i = 0; i < len; i++) {
            if (hit >= 0) {
                hit -= elements[i].getWeight();
            }else {
                index = i - 1;
                break;
            }
        }
        return elements[index].getPeer();
    }
}
